﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using AMM.Business;
using AMM.Business.Config;
using AMM.CustomClassLibrary;
using AMM.Model;
using AMM.UserControls;

namespace AMM.Forms {
    public partial class FrmBase<T> : FrmRootBase {

        private RoleFunction _roleFunc;
        private FrmSearch _frmSearch;

        protected virtual BaseSearchControl SearchControl { get { return null; } }
        protected FlexBindingSource<T> FBS { get; set; }
        protected PrintHelper PrintHelperIns { get; set; }
        protected FrmMDIContainer MDIParent { private set; get; }
        protected FrmEdit FormEdit { get; set; }
        protected string RequiredMessage { get { return "必填"; } }

        protected virtual void Add() {
            this.SetupEnabled();
            this.MDIParent.SetStatusInformation("新建");
        }
        protected virtual void Copy() {
            this.SetupEnabled();
            this.MDIParent.SetStatusInformation("复制");
        }
        protected virtual void Amend() {
            this.SetupEnabled();
            this.MDIParent.SetStatusInformation("修改");
        }
        protected virtual void Save() {
            this.SetupEnabled();
        }
        protected virtual void Delete() {
            this.SetupEnabled();
        }
        protected virtual void Audit() {
            this.SetupEnabled();
        }
        protected virtual void Print() {
            if (this.PrintHelperIns == null) {
                this.ShowError("功能未实现！");
                return;
            }
            this.PrintHelperIns.Run();
        }
        protected virtual void Complete() {
            this.SetupEnabled();
            this.MDIParent.SetStatusInformation("完成");
        }
        protected virtual void Export() {
            this.SetupEnabled();
            this.MDIParent.SetStatusInformation("导出");
        }
        protected virtual void Import() {
            this.SetupEnabled();
            this.MDIParent.SetStatusInformation("导入");
        }
        protected virtual void Search(object sender, FrmSearch.SearchArgs e) {

        }
        protected virtual void ShouldSelectSingleRecord() {
            this.ShowInfo("请选择一条记录！");
        }
        protected virtual void OnlySelectSingleRecord() {
            this.ShowInfo("只能选择一条记录！");
        }
        protected virtual void BindBasics(ListControl control, BasicsType basicsType) {
            control.DataSource = new BasicsProcessor().FetchEnabledBasicsByType(basicsType);
            control.DisplayMember = "Name";
            control.ValueMember = "BasicsId";
        }

        public FrmBase() { this.InitializeComponent(); }

        #region Private methods

        private void SetupPermissions() {
            List<Powers> powerList = new PowerHelper().FetchPowers(this._roleFunc.Powers);
            if (IsSystem) { IsOffline = false; }
            this.tsBtnNew.Visible = powerList.Contains(Powers.Add) && !IsOffline;
            this.tsBtnAmend.Visible = powerList.Contains(Powers.Amend) && !IsOffline;
            this.tsBtnSave.Visible = (powerList.Contains(Powers.Add) || powerList.Contains(Powers.Amend)) && !IsOffline;
            this.tsBtnDelete.Visible = powerList.Contains(Powers.Delete) && !IsOffline;
            this.tsBtnAudit.Visible = powerList.Contains(Powers.Audit) && !IsOffline;
            this.tsBtnSearch.Visible = powerList.Contains(Powers.Search) && !IsOffline;
            this.tsBtnPrint.Visible = powerList.Contains(Powers.Print) && !IsOffline;
            this.tsBtnCopy.Visible = powerList.Contains(Powers.Copy) && !IsOffline;
            this.tsBtnComplete.Visible = powerList.Contains(Powers.Complete) && !IsOffline;
            this.tsBtnExport.Visible = powerList.Contains(Powers.Export) && !IsOffline;
            this.tsBtnImport.Visible = powerList.Contains(Powers.Import) && !IsOffline;
            if (this.FBS == null) { this.tsBtnSave.Visible = false; }
        }

        private void SetupEnabled() {
            this.tsBtnSave.Enabled = this.FBS != null && this.FBS.CurrentItem != null;
        }

        #endregion

        private void FrmBase_Load(object sender, EventArgs e) {
            /*
             * Notice: We must promise that we never execute any long time processing in DesignMode * 
            */
            if (this.DesignMode) { return; }

            this.CreateNewThread(() => {
                // permissions configuration
                this._roleFunc = new FunctionProcessor().FetchPowersByUserAndCode(LoginUserId, this.FunctionCode);
            }, () => {
                this.MDIParent = ((FrmMDIContainer)this.ParentForm);
                this.SetupPermissions();
                this.SetupEnabled();
            });
        }

        private void FrmBase_FormClosing(object sender, FormClosingEventArgs e) {
            if (this.FBS != null && this.FBS.CurrentItem != null) {
                e.Cancel = this.ShowQuestion("有操作未保存，直接退出吗？") == DialogResult.No;
            }
        }

        private void tsBar_ItemClicked(object sender, ToolStripItemClickedEventArgs e) {
            Action actAdd = () => {
                if (this.FBS != null && this.FBS.CurrentItem != null) {
                    if (this.ShowQuestion("有操作未保存，直接退出吗？") == DialogResult.Yes) {
                        this.Add();
                        return;
                    }
                }
                this.Add();
            };

            Action actCopy = () => {
                if (this.FBS != null && this.FBS.CurrentItem != null) {
                    if (this.ShowQuestion("有操作未保存，直接退出吗？") == DialogResult.Yes) {
                        this.Copy();
                        return;
                    }
                }
                this.Copy();
            };

            Action actAmend = () => {
                if (this.FBS != null && this.FBS.CurrentItem != null) {
                    if (this.ShowQuestion("有操作未保存，直接退出吗？") == DialogResult.Yes) {
                        this.Amend();
                        return;
                    }
                }
                this.Amend();
            };

            Action actSave = () => {
                if (this.validator.Validate()) {
                    this.Save();
                }
                else {
                    this.ShowInfo("请正确填写所需的数据！");
                }
            };

            Action actSearch = () => {
                if (this.SearchControl == null) { return; }
                if (this._frmSearch == null) {
                    this._frmSearch = new FrmSearch();
                    this._frmSearch.Controls.Add(this.SearchControl);
                    this._frmSearch.Search += new FrmSearch.SearchEventHandler(Search);
                }
                this._frmSearch.Text = "搜索";
                //this._frmSearch.ShowDialog(this);
                FrmEntry.LoadAndRunDialog(this._frmSearch);
            };

            Action actDelete = () => {
                if (this.ShowQuestion("操作不可逆，确定删除吗？") == DialogResult.Yes) {
                    this.Delete();
                }
            };

            Action actAudit = () => {
                this.Audit();
            };

            Action actPrint = () => {
                this.Print();
            };

            Action actComplete = () => {
                this.Complete();
            };

            Action actExport = () => {
                this.Export();
            };

            Action actImport= () => {
                this.Import();
            };

            this.tsBar.Focus();
            switch (e.ClickedItem.Name) {
                case "tsBtnNew": actAdd.Invoke(); break;
                case "tsBtnCopy": actCopy.Invoke(); break;
                case "tsBtnAmend": actAmend.Invoke(); break;
                case "tsBtnSave": actSave.Invoke(); break;
                case "tsBtnDelete": actDelete.Invoke(); break;
                case "tsBtnAudit": actAudit.Invoke(); break;
                case "tsBtnSearch": actSearch.Invoke(); break;
                case "tsBtnPrint": actPrint.Invoke(); break;
                case "tsBtnComplete": actComplete.Invoke(); break;
                case "tsBtnExport": actExport.Invoke(); break;
                case "tsBtnImport": actImport.Invoke(); break;
                case "tsBtnQuit": this.Close(); break;
            }
        }
    }
}
